<?php

namespace app\admin\controller;

use app\common\ApiBase;
use app\common\ApiStatus;
use app\common\MP3File;
use app\model\SystemAdmin;
use app\model\SystemUploadfile;
use app\service\QCloudCosService;
use support\Redis;
use support\Request;
use support\Response;

class Admin extends ApiBase
{

    public function beforeAction()
    {
        if (empty(request()->admin_uid)) return $this->apiFailed('请先登录', ApiStatus::API_NEED_LOGIN->value);
        parent::beforeAction();
        $this->model      = new SystemAdmin();
        $this->order_sort = 'id desc';
        $this->params     = $this->buildTableParams(-1);
    }

    /**
     * ip白名单添加
     * POST /admin/admin/addWhiteIP
     *
     * @param Request $request
     * @return Response
     */
    public function addWhiteIP(Request $request): Response
    {
        $ip = $request->post('ip', '');
        if (empty($ip)) return $this->apiFailed('ip error');
        Redis::select(7);
        $info = Redis::zScore(WHITE_IP_REDIS_KEY, $ip);
        if (!$info) Redis::zIncrBy(WHITE_IP_REDIS_KEY, 1, $ip);
        $list = Redis::zRevRange(WHITE_IP_REDIS_KEY, 0, -1);
        Redis::select(0);
        return $this->apiSuccess($list);
    }

    public function userInfo(Request $request): Response
    {
        $admin_uid = $request->admin_uid;
        $admin     = $this->model->where(['id' => $admin_uid])->find();
        unset($admin['password']);
        $admin['head_img'] = '';
        return $this->apiSuccess($admin);
    }

    public function uploadPic(Request $request): Response
    {
        $file = $request->file('file');
        if (empty($file)) return $this->apiFailed('获取上传数据错误');
//        $fileName = md5(uniqid(mt_rand(), true)) . Str::random(8) . ".{$file->getUploadExtension()}";
//        try {
//            $upload = OssService::instance()->adminUploadFile($file->getPathname(), $fileName);
//        } catch (OssException $e) {
//            return $this->apiFailed($e->getMessage());
//        }
        try {
            $upload = QCloudCosService::instance()->upload($file);
        } catch (\Throwable $e) {
            return $this->apiFailed('上传失败' . $e->getMessage());
        }
//        $url = $upload['info']['url'] ?? '';
        $url = $upload['href'] ?? '';
        if ($url) $url = str_replace("http://", "https://", $url);

        //获取时长
        $duration = 0;
        if ($file->getUploadExtension() == 'mp3') {
            $mp3      = new MP3File($file->getPathname());
            $duration = $mp3->getDurationEstimate();
        }

        //添加上传文件表
        $systemUploadfileModel                = new SystemUploadfile();
        $systemUploadfileModel->original_name = $file->getUploadName();        //文件原名
        $systemUploadfileModel->file_type     = $file->getUploadExtension();   //文件后缀名
        $systemUploadfileModel->file_size     = $file->getSize();              //文件大小
        $systemUploadfileModel->url           = $url;
        $systemUploadfileModel->admin_uid     = $request->admin_uid;
        $systemUploadfileModel->save();

        return $this->apiSuccess(compact('url', 'duration'));
    }

    public function addAdmin(Request $request): Response
    {
        $username = $request->post('username', '');
        $password = $request->post('password', '');
        $head_img = $request->post('head_img', '');
        if (empty($username) || empty($password)) return $this->apiFailed('账号或者密码不能为空');
        $find = $this->model->where('username', $username)->find();
        if ($find) return $this->apiFailed('当前用户名已存在');
        $password = password_admin($password);
        $data     = [
            'username'    => $username,
            'password'    => $password,
            'head_img'    => $head_img,
            'status'      => 1,
            'create_time' => time(),
            'update_time' => time(),
        ];
        $this->model->insert($data);
        return $this->apiSuccess('添加成功');
    }

    /**
     * 修改密码
     *
     */
    public function changePassword(Request $request): Response
    {
        $username = $request->post('username', '');
        $password = $request->post('password', '');
        if (empty($username) || empty($password)) return $this->apiFailed('账号或者密码错误');

        $admin = SystemAdmin::where(['username' => $username])->find();
        if (empty($admin)) return $this->apiFailed('用户不存在');
        if ($admin->status == 0) return $this->apiFailed('账号已被禁用');
        $admin->password = password_admin($password);
        $admin->save();

        return $this->apiSuccess();
    }

}